/**
 * 基于 mp4-muxer 的先进 MP4 Faststart 优化方案
 * 
 * 特性：
 * - 流式处理，支持大文件（> 2GB）
 * - 异步执行，不阻塞主线程
 * - 不重新编码，只重建索引结构
 * - 正确处理 moov atom 和所有索引表（stco, stss, stts 等）
 * - 与 FFmpeg -movflags +faststart 等效
 * 
 * 技术栈：
 * - mp4-muxer: 流式 MP4 muxing
 * - mp4box.js: MP4 解析
 * - WebCodecs: 媒体处理 API
 */

import { Muxer, ArrayBufferTarget } from 'mp4-muxer'
import * as MP4Box from 'mp4box'

/**
 * 使用 mp4-muxer 实现流式 faststart 优化
 * 
 * @param {File} file - 原始 MP4 文件
 * @param {Object} options - 配置选项
 * @param {Function} options.onProgress - 进度回调 (percent: 0-100, stage: string)
 * @param {boolean} options.useWorker - 是否使用 Web Worker（推荐）
 * @returns {Promise<File>} 优化后的文件
 */
export async function optimizeMP4Advanced(file, options = {}) {
    const {
        onProgress = () => { }
        // useWorker = false // 暂时不使用
    } = options

    // 检查浏览器兼容性
    if (!checkBrowserSupport()) {
        throw new Error('当前浏览器不支持 WebCodecs API，请使用 Chrome 94+, Edge 94+, 或 Safari 16.4+')
    }

    // 暂时禁用 Worker（简化实现）
    // if (useWorker && typeof Worker !== 'undefined') {
    //     return optimizeInWorker(file, onProgress)
    // }

    // 主线程处理
    return optimizeInMainThread(file, onProgress)
}

/**
 * 检查浏览器是否支持 WebCodecs
 */
function checkBrowserSupport() {
    return typeof EncodedVideoChunk !== 'undefined' &&
        typeof EncodedAudioChunk !== 'undefined'
}

/**
 * 在主线程中优化（使用 mp4-muxer）
 */
async function optimizeInMainThread(file, onProgress) {
    console.log('🚀 开始 MP4 Faststart 优化（mp4-muxer 方案）...')
    onProgress(0, '开始解析文件')

    try {
        // 1. 解析原始文件
        onProgress(10, '正在解析 MP4 结构')
        const { fileInfo, tracks, samples, originalBuffer, mp4boxfile } = await parseMP4(file)

        console.log('📊 文件信息:', {
            duration: fileInfo.duration,
            timescale: fileInfo.timescale,
            tracks: fileInfo.tracks.map(t => ({
                id: t.id,
                type: t.type,
                codec: t.codec
            }))
        })

        // 2. 配置 muxer
        onProgress(30, '正在配置 muxer')
        const muxerConfig = buildMuxerConfig(fileInfo, tracks)

        console.log('✓ Muxer 配置:', JSON.stringify(muxerConfig, null, 2))

        // 验证配置
        if (!muxerConfig.video && !muxerConfig.audio) {
            throw new Error('无法提取视频或音频配置')
        }

        const target = new ArrayBufferTarget()

        const muxer = new Muxer({
            target,
            fastStart: 'in-memory', // 关键：启用 faststart
            ...muxerConfig
        })

        console.log('✓ Muxer 创建成功')

        // 4. 重新 mux（不重新编码）
        onProgress(50, '正在重建索引结构')
        const { videoCount, audioCount } = await remuxSamples(muxer, samples, tracks, originalBuffer, mp4boxfile, (progress) => {
            const percent = 50 + progress * 40
            onProgress(percent, `正在处理 (${Math.round(progress * 100)}%)`)
        })

        // 5. 完成
        onProgress(90, '正在完成处理')
        muxer.finalize()

        // 6. 创建新文件
        onProgress(95, '正在生成文件')
        const optimizedBuffer = target.buffer

        console.log('✓ 生成的文件大小:', optimizedBuffer.byteLength, 'bytes')
        console.log('✓ 原始文件大小:', file.size, 'bytes')

        // 验证文件不为空
        if (optimizedBuffer.byteLength === 0) {
            throw new Error('生成的文件为空')
        }

        const optimizedBlob = new Blob([optimizedBuffer], { type: 'video/mp4' })
        const optimizedFile = new File(
            [optimizedBlob],
            file.name.replace('.mp4', '_faststart.mp4'),
            { type: 'video/mp4' }
        )

        onProgress(100, '优化完成')
        console.log('✅ 优化完成')
        console.log('  - 原始文件:', file.size, 'bytes')
        console.log('  - 优化后:', optimizedFile.size, 'bytes')
        console.log('  - 视频 samples:', videoCount)
        console.log('  - 音频 samples:', audioCount)

        return optimizedFile

    } catch (error) {
        console.error('❌ 优化失败:', error)
        throw new Error(`MP4 优化失败: ${error.message}`)
    }
}

/**
 * 使用 Web Worker 优化（暂未实现）
 */
// async function optimizeInWorker(file, onProgress) {
//     return new Promise((resolve, reject) => {
//         // 创建 Worker
//         const worker = new Worker(
//             new URL('./mp4FastStartWorker.js', import.meta.url),
//             { type: 'module' }
//         )

//         // 监听消息
//         worker.onmessage = (e) => {
//             const { type, data } = e.data

//             switch (type) {
//                 case 'progress':
//                     onProgress(data.percent, data.stage)
//                     break

//                 case 'success':
//                     worker.terminate()
//                     resolve(data.file)
//                     break

//                 case 'error':
//                     worker.terminate()
//                     reject(new Error(data.message))
//                     break
//             }
//         }

//         worker.onerror = (error) => {
//             worker.terminate()
//             reject(error)
//         }

//         // 发送文件
//         worker.postMessage({ file })
//     })
// }

/**
 * 解析 MP4 文件
 */
async function parseMP4(file) {
    return new Promise((resolve, reject) => {
        const mp4boxfile = MP4Box.createFile()

        let fileInfo = null
        let originalBuffer = null
        const tracks = new Map()
        const samples = new Map()

        mp4boxfile.onReady = (info) => {
            console.log('📦 MP4 文件信息:', info)
            fileInfo = info

            // 设置提取选项
            info.tracks.forEach(track => {
                tracks.set(track.id, track)
                samples.set(track.id, [])

                // 打印 track 的所有属性，查找 avcC/esds
                console.log(`Track ${track.id} 属性:`, Object.keys(track))

                // 检查是否有 avcC 或 esds
                if (track.type === 'video') {
                    console.log('视频 track 详细信息:', {
                        codec: track.codec,
                        width: track.video?.width,
                        height: track.video?.height,
                        hasAvcC: !!track.avcC,
                        avcCKeys: track.avcC ? Object.keys(track.avcC) : [],
                        videoKeys: track.video ? Object.keys(track.video) : []
                    })

                    // 深入检查 video 对象
                    if (track.video) {
                        console.log('track.video 完整内容:', track.video)
                    }
                } else if (track.type === 'audio') {
                    console.log('音频 track 详细信息:', {
                        codec: track.codec,
                        sampleRate: track.audio?.sample_rate,
                        hasEsds: !!track.esds,
                        esdsKeys: track.esds ? Object.keys(track.esds) : [],
                        audioKeys: track.audio ? Object.keys(track.audio) : []
                    })

                    // 深入检查 audio 对象
                    if (track.audio) {
                        console.log('track.audio 完整内容:', track.audio)
                    }
                }

                mp4boxfile.setExtractionOptions(track.id, null, {
                    nbSamples: Infinity
                })
            })

            mp4boxfile.start()
        }

        mp4boxfile.onSamples = (trackId, _ref, trackSamples) => {
            const sampleList = samples.get(trackId)
            const track = tracks.get(trackId)

            if (sampleList) {
                // 避免栈溢出：不使用 spread operator
                for (let i = 0; i < trackSamples.length; i++) {
                    sampleList.push(trackSamples[i])
                }

                // 统计关键帧
                if (track && track.type === 'video') {
                    const keyFrames = trackSamples.filter(s => s.is_sync)
                    console.log(`📊 Track ${trackId}: 收集 ${trackSamples.length} 个 samples (总计: ${sampleList.length}), 其中 ${keyFrames.length} 个关键帧`)

                    // 打印关键帧位置
                    if (keyFrames.length > 0) {
                        keyFrames.forEach(kf => {
                            const time = (kf.cts / kf.timescale)
                            console.log(`  🔑 关键帧 at ${time.toFixed(2)}s (cts: ${kf.cts})`)
                        })
                    }
                } else {
                    console.log(`📊 Track ${trackId}: 收集 ${trackSamples.length} 个 samples (总计: ${sampleList.length})`)
                }
            }
        }

        mp4boxfile.onError = (e) => {
            console.error('❌ MP4Box 错误:', e)
            reject(new Error(`MP4 解析失败: ${e}`))
        }

        // 读取文件
        const reader = new FileReader()
        reader.onload = (e) => {
            originalBuffer = e.target.result
            const arrayBuffer = originalBuffer.slice(0)
            arrayBuffer.fileStart = 0

            mp4boxfile.appendBuffer(arrayBuffer)
            mp4boxfile.flush()

            // 等待处理完成
            setTimeout(() => {
                console.log('✓ 解析完成，tracks:', tracks.size, 'samples:', Array.from(samples.values()).reduce((sum, s) => sum + s.length, 0))

                // 尝试从 MP4Box 内部获取 avcC
                console.log('🔍 检查 MP4Box 内部结构...')
                if (mp4boxfile.moov && mp4boxfile.moov.traks) {
                    mp4boxfile.moov.traks.forEach((trak, index) => {
                        console.log(`Trak ${index}:`, {
                            hasStsd: !!trak.mdia?.minf?.stbl?.stsd,
                            stsdEntries: trak.mdia?.minf?.stbl?.stsd?.entries?.length
                        })

                        // 检查 stsd entries
                        const entries = trak.mdia?.minf?.stbl?.stsd?.entries
                        if (entries && entries.length > 0) {
                            console.log('STSD Entry 0:', entries[0])
                            console.log('Entry 0 keys:', Object.keys(entries[0]))

                            // 查找 avcC
                            if (entries[0].avcC) {
                                console.log('✓ 找到 avcC!', entries[0].avcC)
                                console.log('avcC 属性:', Object.keys(entries[0].avcC))
                                console.log('avcC 详细:', {
                                    AVCProfileIndication: entries[0].avcC.AVCProfileIndication,
                                    profile_compatibility: entries[0].avcC.profile_compatibility,
                                    AVCLevelIndication: entries[0].avcC.AVCLevelIndication,
                                    hasSPS: !!entries[0].avcC.SPS,
                                    hasPPS: !!entries[0].avcC.PPS,
                                    SPSCount: entries[0].avcC.SPS?.length,
                                    PPSCount: entries[0].avcC.PPS?.length
                                })

                                // 打印 SPS 和 PPS 的详细信息
                                if (entries[0].avcC.SPS && entries[0].avcC.SPS.length > 0) {
                                    console.log('SPS[0]:', entries[0].avcC.SPS[0])
                                    console.log('SPS[0] keys:', Object.keys(entries[0].avcC.SPS[0]))
                                }
                                if (entries[0].avcC.PPS && entries[0].avcC.PPS.length > 0) {
                                    console.log('PPS[0]:', entries[0].avcC.PPS[0])
                                    console.log('PPS[0] keys:', Object.keys(entries[0].avcC.PPS[0]))
                                }
                            }
                        }
                    })
                }

                resolve({ fileInfo, tracks, samples, originalBuffer, mp4boxfile })
            }, 500)
        }

        reader.onerror = () => reject(new Error('文件读取失败'))
        reader.readAsArrayBuffer(file)
    })
}

/**
 * 构建 muxer 配置
 */
function buildMuxerConfig(fileInfo, tracks) {
    const config = {}

    for (const track of tracks.values()) {
        if (track.type === 'video') {
            config.video = {
                codec: track.codec.startsWith('avc') ? 'avc' :
                    track.codec.startsWith('hev') ? 'hevc' :
                        track.codec.startsWith('vp09') ? 'vp9' : 'avc',
                width: track.video.width,
                height: track.video.height,
                frameRate: track.video.fps || 30
            }
        } else if (track.type === 'audio') {
            config.audio = {
                codec: track.codec.startsWith('mp4a') ? 'aac' :
                    track.codec.startsWith('opus') ? 'opus' : 'aac',
                sampleRate: track.audio.sample_rate,
                numberOfChannels: track.audio.channel_count
            }
        }
    }

    return config
}



/**
 * 从 MP4Box 内部结构中提取 avcC box (H.264 配置)
 * 这是关键：包含 SPS/PPS 数据，视频解码必需
 */
function extractAvcCFromMP4Box(mp4boxfile, trackId) {
    try {
        console.log('🔍 从 MP4Box 内部提取 avcC...')

        if (!mp4boxfile || !mp4boxfile.moov || !mp4boxfile.moov.traks) {
            console.warn('⚠️ MP4Box 结构不完整')
            return undefined
        }

        // 找到对应的 trak
        const trak = mp4boxfile.moov.traks.find(t => t.tkhd && t.tkhd.track_id === trackId)
        if (!trak) {
            console.warn(`⚠️ 未找到 track ${trackId}`)
            return undefined
        }

        // 导航到 stsd
        const stsd = trak.mdia?.minf?.stbl?.stsd
        if (!stsd || !stsd.entries || stsd.entries.length === 0) {
            console.warn('⚠️ 未找到 stsd entries')
            return undefined
        }

        // 获取第一个 entry（通常是 avc1 或 avc3）
        const entry = stsd.entries[0]
        console.log('STSD entry type:', entry.type)

        // 查找 avcC
        if (entry.avcC) {
            console.log('✓ 找到 avcC!', entry.avcC)

            // avcC 包含配置数据，需要转换为 Uint8Array
            // MP4Box.js 的 avcC 对象包含 SPS 和 PPS
            if (entry.avcC.SPS && entry.avcC.PPS) {
                console.log('✓ 找到 SPS 和 PPS')
                console.log('  SPS 数量:', entry.avcC.SPS.length)
                console.log('  PPS 数量:', entry.avcC.PPS.length)

                // 构建 avcC box 数据
                return buildAvcCBox(entry.avcC)
            }
        }

        console.warn('⚠️ 未找到 avcC 数据')
        return undefined
    } catch (error) {
        console.error('提取 avcC 失败:', error)
        return undefined
    }
}

/**
 * 构建 avcC box 数据
 */
function buildAvcCBox(avcC) {
    try {
        // avcC box 格式：
        // - configurationVersion (1 byte)
        // - AVCProfileIndication (1 byte)
        // - profile_compatibility (1 byte)
        // - AVCLevelIndication (1 byte)
        // - lengthSizeMinusOne (1 byte)
        // - numOfSequenceParameterSets (1 byte)
        // - SPS data
        // - numOfPictureParameterSets (1 byte)
        // - PPS data

        const spsArray = avcC.SPS || []
        const ppsArray = avcC.PPS || []

        // 计算总大小
        let totalSize = 7 // 固定头部
        spsArray.forEach(sps => {
            const spsLength = sps.length || (sps.data ? sps.data.length : 0)
            totalSize += 2 + spsLength // 2 bytes length + data
        })
        totalSize += 1 // PPS count
        ppsArray.forEach(pps => {
            const ppsLength = pps.length || (pps.data ? pps.data.length : 0)
            totalSize += 2 + ppsLength // 2 bytes length + data
        })

        const buffer = new Uint8Array(totalSize)
        let offset = 0

        // 写入头部
        buffer[offset++] = 1 // configurationVersion
        buffer[offset++] = avcC.AVCProfileIndication || 100
        buffer[offset++] = avcC.profile_compatibility || 0
        buffer[offset++] = avcC.AVCLevelIndication || 40
        buffer[offset++] = 0xFF // lengthSizeMinusOne (4 bytes)

        // 写入 SPS
        buffer[offset++] = 0xE0 | (spsArray.length & 0x1F) // numOfSequenceParameterSets
        spsArray.forEach(sps => {
            // MP4Box.js 的 SPS 结构: { length: number, data: Uint8Array }
            const spsData = sps.data || sps.nalu || sps
            const spsLength = sps.length || spsData.length
            buffer[offset++] = (spsLength >> 8) & 0xFF
            buffer[offset++] = spsLength & 0xFF
            buffer.set(spsData, offset)
            offset += spsLength
        })

        // 写入 PPS
        buffer[offset++] = ppsArray.length & 0xFF // numOfPictureParameterSets
        ppsArray.forEach(pps => {
            // MP4Box.js 的 PPS 结构: { length: number, data: Uint8Array }
            const ppsData = pps.data || pps.nalu || pps
            const ppsLength = pps.length || ppsData.length
            buffer[offset++] = (ppsLength >> 8) & 0xFF
            buffer[offset++] = ppsLength & 0xFF
            buffer.set(ppsData, offset)
            offset += ppsLength
        })

        console.log('✓ 构建 avcC box 完成，大小:', buffer.length, 'bytes')
        return buffer
    } catch (error) {
        console.error('构建 avcC box 失败:', error)
        return undefined
    }
}

/**
 * 从原始文件中提取 esds box (AAC 配置)
 */
function extractEsds(buffer, track) {
    try {
        // MP4Box.js 已经解析了 esds
        if (track.codec.startsWith('mp4a')) {
            if (track.esds) {
                console.log('✓ 找到 esds 数据')
                return track.esds
            }
        }

        return undefined
    } catch (error) {
        console.error('提取 esds 失败:', error)
        return undefined
    }
}

/**
 * 重新 mux samples（不重新编码）
 * 优化策略：
 * 1. 音视频交错处理，而不是先视频后音频
 * 2. 更精确的时间戳计算
 * 3. 修复 duration 计算
 */
async function remuxSamples(muxer, samplesMap, tracks, originalBuffer, mp4boxfile, onProgress) {
    // 计算总 samples
    let totalSamples = 0
    for (const samples of samplesMap.values()) {
        totalSamples += samples.length
    }

    console.log(`📝 开始重新 mux，总计 ${totalSamples} 个 samples`)
    console.log(`🎯 优化策略：音视频交错处理 + 精确时间戳`)

    let processedSamples = 0
    let videoSampleCount = 0
    let audioSampleCount = 0

    // 获取视频和音频 tracks
    const videoTracks = Array.from(samplesMap.entries()).filter(([trackId]) => {
        const track = tracks.get(trackId)
        return track && track.type === 'video'
    })

    const audioTracks = Array.from(samplesMap.entries()).filter(([trackId]) => {
        const track = tracks.get(trackId)
        return track && track.type === 'audio'
    })

    // 对每个 track 的 samples 按时间戳排序并修复 duration
    console.log('📊 对 samples 进行排序和预处理...')
    const allTracks = [...videoTracks, ...audioTracks]

    for (const [trackId, samples] of allTracks) {
        const track = tracks.get(trackId)
        console.log(`预处理 track ${trackId} (${track.type})...`)

        // 按 CTS 排序（显示时间）
        samples.sort((a, b) => a.cts - b.cts)

        // 修复 duration：使用下一个 sample 的 CTS - 当前 CTS
        for (let i = 0; i < samples.length - 1; i++) {
            const currentSample = samples[i]
            const nextSample = samples[i + 1]

            // 计算实际 duration
            const calculatedDuration = nextSample.cts - currentSample.cts

            // 如果原始 duration 不准确，使用计算值
            if (Math.abs(currentSample.duration - calculatedDuration) > 1) {
                console.log(`修正 sample ${i} duration: ${currentSample.duration} -> ${calculatedDuration}`)
                currentSample.duration = calculatedDuration
            }
        }

        // 最后一个 sample 使用平均 duration
        if (samples.length > 1) {
            const avgDuration = samples.slice(0, -1).reduce((sum, s) => sum + s.duration, 0) / (samples.length - 1)
            samples[samples.length - 1].duration = Math.round(avgDuration)
        }

        console.log(`✓ Track ${trackId} 预处理完成: ${samples.length} samples`)
    }

    // 🎯 新策略：音视频交错处理
    // 创建统一的 sample 队列，按时间戳排序
    const allSamples = []

    for (const [trackId, samples] of allTracks) {
        const track = tracks.get(trackId)
        samples.forEach(sample => {
            allSamples.push({
                trackId,
                track,
                sample,
                timestamp: (sample.cts * 1000000) / sample.timescale // 微秒
            })
        })
    }

    // 按时间戳排序，实现音视频交错
    console.log('🔄 按时间戳排序所有 samples（音视频交错）...')
    allSamples.sort((a, b) => a.timestamp - b.timestamp)

    console.log(`✓ 总计 ${allSamples.length} 个 samples 已排序`)

    // 跟踪每个 track 是否已添加第一个 sample
    const firstSampleAdded = new Map()

    // 按时间顺序处理所有 samples
    for (let i = 0; i < allSamples.length; i++) {
        const { trackId, track, sample, timestamp } = allSamples[i]
        const isVideo = track.type === 'video'
        const isFirstSample = !firstSampleAdded.get(trackId)

        try {
            // 从原始 buffer 中提取 sample 数据
            const sampleData = new Uint8Array(
                originalBuffer,
                sample.offset,
                sample.size
            )

            // 使用更精确的时间戳计算
            // 使用 Math.round 避免浮点误差累积
            const duration = Math.round((sample.duration * 1000000) / sample.timescale)

            // 构造 chunk 数据
            const chunkData = {
                type: sample.is_sync ? 'key' : 'delta',
                timestamp: Math.round(timestamp), // 四舍五入避免精度问题
                duration: duration > 0 ? duration : undefined,
                data: sampleData
            }

            // 调试：打印关键位置的 samples
            const timeInSeconds = timestamp / 1000000

            // 打印所有关键帧（视频）
            if (sample.is_sync && isVideo) {
                console.log(`🔑 视频关键帧 at ${timeInSeconds.toFixed(2)}s (sample ${i}, size: ${sampleData.byteLength} bytes)`)
            }

            // 打印卡顿位置附近的 samples（更详细）
            if ((timeInSeconds >= 74 && timeInSeconds <= 81)) {
                const sampleInfo = {
                    timestamp: timeInSeconds.toFixed(3) + 's',
                    cts: sample.cts,
                    duration: duration ? (duration / 1000).toFixed(3) + 'ms' : 'N/A',
                    type: chunkData.type,
                    is_sync: sample.is_sync,
                    size: sampleData.byteLength,
                    trackId
                }

                // 如果是视频，添加更多信息
                if (isVideo) {
                    sampleInfo.sampleNumber = sample.number
                    sampleInfo.description = sample.description ? 'YES' : 'NO'
                }

                console.log(`${isVideo ? '📹 视频' : '🔊 音频'} sample ${i}:`, sampleInfo)
            }

            // 添加到 muxer
            if (isVideo) {
                try {
                    // eslint-disable-next-line no-undef
                    const chunk = new EncodedVideoChunk(chunkData)

                    // 为第一个 chunk 添加配置元数据
                    if (isFirstSample) {
                        const description = extractAvcCFromMP4Box(mp4boxfile, trackId)

                        const decoderConfig = {
                            codec: track.codec,
                            codedWidth: track.video.width,
                            codedHeight: track.video.height,
                            displayAspectWidth: track.video.width,
                            displayAspectHeight: track.video.height,
                            colorSpace: {
                                primaries: 'bt709',
                                transfer: 'bt709',
                                matrix: 'bt709',
                                fullRange: false
                            },
                            hardwareAcceleration: 'prefer-hardware'
                        }

                        if (description) {
                            decoderConfig.description = description
                            console.log('✓ 使用提取的 avcC 数据')
                        } else {
                            console.warn('⚠️ 未找到 avcC 数据')
                        }

                        console.log('添加第一个视频 chunk，配置:', decoderConfig)
                        muxer.addVideoChunk(chunk, { decoderConfig })
                        firstSampleAdded.set(trackId, true)
                    } else {
                        muxer.addVideoChunk(chunk)
                    }

                    videoSampleCount++
                } catch (error) {
                    console.error(`添加视频 chunk ${i} 失败:`, error)
                }
            } else {
                // eslint-disable-next-line no-undef
                const chunk = new EncodedAudioChunk(chunkData)

                if (isFirstSample) {
                    const description = extractEsds(originalBuffer, track)

                    const decoderConfig = {
                        codec: track.codec,
                        sampleRate: track.audio.sample_rate,
                        numberOfChannels: track.audio.channel_count
                    }

                    if (description) {
                        decoderConfig.description = description
                        console.log('✓ 使用提取的 esds 数据')
                    }

                    console.log('添加第一个音频 chunk，配置:', decoderConfig)
                    muxer.addAudioChunk(chunk, { decoderConfig })
                    firstSampleAdded.set(trackId, true)
                } else {
                    muxer.addAudioChunk(chunk)
                }

                audioSampleCount++
            }

            processedSamples++
            if (processedSamples % 500 === 0) {
                onProgress(processedSamples / totalSamples)
                console.log(`处理进度: ${processedSamples}/${totalSamples} (${(processedSamples / totalSamples * 100).toFixed(1)}%)`)
            }
        } catch (error) {
            console.error(`处理 sample ${i} 失败:`, error)
            console.error('Sample 信息:', {
                trackId,
                type: track.type,
                offset: sample.offset,
                size: sample.size,
                cts: sample.cts,
                duration: sample.duration,
                is_sync: sample.is_sync,
                timestamp: timestamp / 1000000 + 's'
            })
            throw error
        }
    }

    onProgress(1)
    console.log(`✓ Remux 完成: ${videoSampleCount} 视频 samples, ${audioSampleCount} 音频 samples`)

    return {
        videoCount: videoSampleCount,
        audioCount: audioSampleCount
    }
}

/**
 * 混合策略：根据文件大小选择最佳方案
 */
export async function optimizeMP4Smart(file, options = {}) {
    const fileSizeMB = file.size / (1024 * 1024)

    console.log(`📊 文件大小: ${fileSizeMB.toFixed(2)} MB`)

    // 小于 500MB：使用前端优化
    if (fileSizeMB < 500) {
        console.log('✅ 使用前端优化方案')
        return optimizeMP4Advanced(file, {
            ...options,
            useWorker: true // 使用 Worker
        })
    }

    // 大于 500MB：建议使用服务端
    console.log('⚠️ 文件较大，建议使用服务端优化')
    throw new Error('文件过大（> 500MB），建议使用服务端优化方案')
}
